<?php
require $_SERVER['DOCUMENT_ROOT'].'/../_core/common.php';

//权限验证
if( Role::init() == false ){
	exit('没有权限');
}

require $_SERVER['DOCUMENT_ROOT'].'/../_interface/pages.php';
require $_SERVER['DOCUMENT_ROOT'].'/../_interface/name.php';

$db = new DB('news');

$category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 0;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;//当前页码
$pageSize = 20;//每页条数

if( $category_id < 1 ){
	$sql_where_orders = ' order by created desc';
}else{
	$sql_where_orders = ' and category_id='.$category_id.' order by index_top desc,orders desc,created desc';
}

//查询总记录数
$total_sql = 'select title_id from news where is_del=1'.$sql_where_orders;
$total = $db->query($total_sql)->getCount();

//分页html
$page_html = Pages::page($page, $total, $pageSize, '/admin/news/news_lists.php?category_id='.$category_id);

//查询当前页记录
$news_sql = 'select category_id,title_id,title,index_top,static_url,empty_id,title_history_id,orders,is_publish,publish_time,created,create_uid from news where is_del=1'.$sql_where_orders.' limit '.(($page-1)*$pageSize).','.$pageSize;
$news_rs = $db->query($news_sql)->getAll();

if( $category_id < 1 ){
	$category_name = '文章总列表（按发布时间排）';
}else{
	//当前栏目名称
	$category_name_sql = 'select title from categories where id='.$category_id.' and is_del=1 limit 1';
	$category_name_rs = $db->query($category_name_sql)->getOne();
	$category_name = $category_name_rs['title'];
}

foreach( $news_rs as $key=>$val ){
	//查询姓名
	$create_username = Name::get_username($db, $val['create_uid']);
	$news_rs[$key]['create_username'] = $create_username;
	
	//查询点击数
	if( $val['category_id'] != 30 ){
		//总表点击
		$news_total_clicks_sql = 'select id,click_views from news_total_clicks where title_id="'.$val['title_id'].'" limit 1';
		$news_total_clicks_rs = $db->query($news_total_clicks_sql)->getOne();
		
		if( $news_total_clicks_rs['id'] < 1 ){
			//新闻表点击
			$news_clicks_sql = 'select views,click_views from news where title_id="'.$val['title_id'].'" and is_del=1 limit 1';
			$news_clicks_rs = $db->query($news_clicks_sql)->getOne();
			
			//新增到总表
			$news_click_data = array('title_id'=>$val['title_id'],
									'views'=>$news_clicks_rs['views'],
									'click_views'=>$news_clicks_rs['click_views'],
									);
			$db->table('news_total_clicks')->insert($news_click_data)->run();//插入
			
			$news_rs[$key]['click'] = $news_clicks_rs['click_views'];
		}else{
			$news_rs[$key]['click'] = $news_total_clicks_rs['click_views'];
		}
	}else{
		$news_rs[$key]['click'] = 0;
	}
}

//记录动作日志
Log::logs_articles($category_id, 1);

require template('admin/news/news_lists');